package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.util.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yu yang
 * @date 2022/9/26 -21:47
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截的请求路径 {}",request.getRequestURL());
        Object employee = request.getSession().getAttribute("employee");
        if (employee != null){
            BaseContext.setCurrentId((Long) employee);
            return true;
        }
        User user = (User) request.getSession().getAttribute("user");
        if (user != null){
            BaseContext.setCurrentId(user.getId());
            return true;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
